//
//  UserAccount.swift
//  微博项目/Users/zhao/Desktop/微博项目/微博项目/微博项目/Classes/Model/UserAccount.swift
//
//  Created by zhaoyinpeng on 16/3/11.
//  Copyright © 2016年 zhaoyinpeng. All rights reserved.
//

/*
  字典转模型
  保存数据
   对外提供获取数据的方式

*/

import UIKit
import AFNetworking

private let userInfoKey = "cn.itcast.account"

class UserAccount: NSObject {
 
    
     //.定义单例对象
    static let shareAccout = UserAccount()
    
    //.用于调用access_token 接口获取授权后的acces_token   用户访问接口权限的标
    
    var access_token: String?
    
    //.access_token的生命周期 单位秒数 当前用户token 过多少秒后会过期
    var expires_in: NSTimeInterval = 0 {
        didSet {
            //.计算过期日期
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
            
        }
    }
    
    //.token过期日期
    var expires_date: NSDate?
    
    //.当前授权用户的UID
    var uid: String?
    
    //.当前登录用户的名称
    var name: String?
    
    //.用户头像
    var avatar_large: String? {
        didSet {
            headImageURL = NSURL(string: avatar_large ?? "")
        }
    }
    
    
    //.计算型属性
    
    var headImageURL: NSURL?
//    var headImageURL: NSURL? {
//        return NSURL(string: avatar_large ?? "")
//    }
    
    
    //.计算型属性
    var userLogin: Bool {
        //.token 不为空 就标示用户登录
        //.token 为空就标示用户未登录
        return access_token != nil
    }
    
    //.为了保证单例对象唯一  需要私有化构造函数
    override private init() {
        super.init()
        //.加载用户信息
        self.loadUserInfo()
    }
    
    //.实现过滤不存在key的方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String {
        //.只读属性
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        
        return accountDict.description
    }
    }




//.保存数据，获取数据
extension UserAccount {
    
    //.MARK: 保存用户信息
    func saveUserInfo(dict: [String : AnyObject]) {
        
        //.给当前对象KVC设置初始值 - 未登录状态 -》 登录状态
        self.setValuesForKeysWithDictionary(dict)
        
        //.保存当前对象的所有属性   以字典的形式
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        //.获取当前对象的字典信息
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        
        //.将用户信息保存到沙盒中  沙盒中不能够存储自定义对象
        userDefaults.setObject(accountDict, forKey: userInfoKey)
        
        //.同步沙盒
        userDefaults.synchronize()
        
        //.测试打印
        print(NSHomeDirectory())
        
        
    }
    
    
    //.提供对外访问的方式
    func loadUserInfo() {
        //.从偏好设置中获取字典信息
        //.从磁盘获取数据  做IO操作  效率低  并且很消耗磁盘
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            return
        }
        //.将字典信息转换成模型数据
        self.setValuesForKeysWithDictionary(dict)
        
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            //.过期日期大于 当前日期
            print("token 正常")
        } else {
            print("用户token 已过期")
            self.access_token = nil
        }
    }
}

//.用户账户相关的所有的网络请求
extension UserAccount {
    
    func loadAccessToken(code: String, finished: (isSuccess: Bool) -> () ) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //.参数字典
        let parameters = ["client_id" : client_id, "client_secret": client_secret,"grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        
        //.发起网络请求
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        //.发起post请求
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            print(result?.classForCoder)
            
            //.获取token
            guard let dict = result as? [String : AnyObject] else {
                //.失败需要执行闭包
                finished(isSuccess: false)
                return
            }
            
            //.标示用户访问接口的权限的一个时效性的标识
            self.loadUserInfo(dict, finished: finished)
            }) { (_, error) -> Void in
                //.失败需要执行闭包
                finished(isSuccess: false)
                print(error)
                
        }
        
    }
    
    private func loadUserInfo(dict: [String: AnyObject],finished:(isSuccess: Bool) -> ()) {
        
        let token = dict["access_token"] as! String
        
        //.获取到用户接口访问权限之后 使用token 获取用户信息
        let uid = dict["uid"] as! String

print(token)
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["access_token" : token, "uid" : uid]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //接口返回的数据确定为 字典类型
            guard var userInfoDict = result as? [String : AnyObject]
                else{
                finished(isSuccess: false)
                return
            }
            print(userInfoDict)
            //.合并字典
            for (k,v) in dict {
                userInfoDict[k] = v
            }
            
            
            
            //.保存字典到沙盒
            //.沙盒中不能够储存空数据
            UserAccount.shareAccout.saveUserInfo(userInfoDict)
            
            //.获取用户信息成功
            finished(isSuccess: true)
            }) { (_, error) -> Void in
                //执行失败的回调
                finished(isSuccess: false)
                print(error)
        }
        
        
        
    }
    
}






